/*
 *
 *  *    Copyright 2020-2021 Luter.me
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */

package com.example.servletdemo.controller;

import com.example.servletdemo.service.SysUserService;
import com.luter.heimdall.core.annotation.CurrentToken;
import com.luter.heimdall.core.authorization.provider.model.UserDO;
import com.luter.heimdall.core.details.UserDetails;
import com.luter.heimdall.core.exception.HeimdallException;
import com.luter.heimdall.core.exception.HeimdallExcessiveAttemptsException;
import com.luter.heimdall.core.limiter.PasswordRetryLimiter;
import com.luter.heimdall.core.manager.AuthenticationManager;
import com.luter.heimdall.core.token.SimpleToken;
import com.luter.heimdall.core.utils.ObjUtil;
import com.luter.heimdall.core.utils.crypto.Md5Util;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
@Slf4j
@RequiredArgsConstructor
public class IndexController {

    private final AuthenticationManager authManager;
    private final SysUserService sysUserService;
    private final PasswordRetryLimiter retryLimiter;

    @GetMapping({"", "/", "/index"})
    public String index(Model model) {
        final SimpleToken token = authManager.getCurrentToken(false);
        if (null != token) {
            model.addAttribute("token", token);
            return "pages/index";
        }
        return "redirect:/login";
    }

    @GetMapping("/login")
    public String toLogin() {
        if (authManager.isAuthenticated(false)) {
            return "redirect:/";
        }
        return "pages/login";
    }

    @PostMapping("/login")
    public String login(String username, String password) {
        final UserDO userByName = sysUserService.getUserByName(username);
        //看看是不是已经锁定了，锁定了，等!
        final int count = retryLimiter.availableTimes(userByName.getUsername());
        if (count <= 0) {
            throw new HeimdallException("Your account is locked. Please try again later");
        }
        //密码是不是错了
        if (!Md5Util.matches(password, userByName.getPassword())) {
            //还可以重试，那单纯就是密码不对
            if (!retryLimiter.overLimitWhenIncremented(userByName.getUsername())) {
                throw new HeimdallException("username or password is incorrect." +
                        " ensure both user account and password are valid.=" + count);
            }
            throw new HeimdallExcessiveAttemptsException();
        }
        ///构造用户详情
        final UserDetails userDetails = new UserDetails(userByName.getAppId(), userByName.getUserId())
                .setAttributes(ObjUtil.ConvertObjectToMap(userByName, "password"));
        authManager.login(userDetails);
        //登录成功后,次数清零
        retryLimiter.release(userByName.getUsername());
        return "redirect:/index";
    }

    @GetMapping("/logout")
    public String logout() {
        authManager.logout();
        return "redirect:/login";
    }

    @GetMapping("/online")
    public String online(Model model, String appId) {
        model.addAttribute("tokens", authManager.getTokenStore().getActiveTokens(appId));
        return "pages/online";
    }

    @GetMapping("/kick/{tid}")
    public String online(@PathVariable String tid) {
        authManager.kickToken(tid);
        return "redirect:/online";
    }

    @GetMapping("/tag")
    public String toTag() {
        return "pages/tag";
    }

    @GetMapping("/anno")
    public String toAnno(Model model, @CurrentToken SimpleToken token) {
        model.addAttribute("pageToken", token);
        return "pages/anno";
    }
}
